package com.sky.common.task;

import com.sky.business.sys.domain.TrackTask;
import com.sky.business.sys.service.DispatcherService;
import com.sky.business.sys.service.TrackTaskService;
import com.sky.common.enums.DispatchType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备任务优先级管理器
 *
 */
@Slf4j
@Component
public class DeviceTaskPriorityMonitor {

    @Autowired
    private TrackTaskService trackTaskService;

    @Autowired
    private DispatcherService dispatcherService;


    @Scheduled(cron = "*/10 * * * * ?")
    public void doTask() {
        List<String> deviceIdList = trackTaskService.getMultiTaskingDevices();
        for (String deviceId : deviceIdList) {
            List<TrackTask> trackTaskList = trackTaskService.findByDeviceId(deviceId);
            if (trackTaskList.size() > 1) {
                TrackTask firstTrackTask = trackTaskList.get(0);
                if (firstTrackTask.getDispatchType() == DispatchType.CMCC) {
                    log.warn("停掉边缘中心指定的任务,保留凌云平台指定的任务");
                    List<TrackTask> edgeTrackTaskList = trackTaskList.stream().filter(task -> task.getDispatchType() != DispatchType.CMCC).collect(Collectors.toList());
                    dispatcherService.endTracking(edgeTrackTaskList);
                }else{
                    log.warn("保留1个任务,停掉其他的任务");
                    List<TrackTask> otherTrackTaskList = trackTaskList.stream().filter(task -> !task.getTaskId().equals(firstTrackTask.getTaskId()) ).collect(Collectors.toList());
                    dispatcherService.endTracking(otherTrackTaskList);
                }
            }
        }
    }
}
